<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div v-loading="loading" element-loading-text="拼命运行中..." class="p4 pos-relative">
    <el-form ref="cadConversionFormRef" :model="caeConversionFormData" :rules="rules">
      <div class="b-1 b-#cccccc b-solid pt2 pl2 mb3">
        <el-form-item prop="caeInputModelType" label="输入模型格式">
          <el-radio-group v-model="caeConversionFormData.caeInputModelType" :disabled="loading" @change="handleRadioChange">
            <el-radio v-for="(item, index) in caeInputModelTypes" :key="'radio-item-input' + index" :value="item.inputModel">{{
              item.inputModel
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="b-1 b-#cccccc b-solid pt2 pl2 mb3">
        <el-form-item prop="caeOutputModelType" label="输出模型格式">
          <el-radio-group v-model="caeConversionFormData.caeOutputModelType" :disabled="loading">
            <el-radio v-for="(item, index) in caeOutputModelTypes" :key="'radio-item-input' + index" :disabled="item.disabled" :value="item.label">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="b-1 b-#cccccc b-solid pt2 pl2 pr2 mb">
        <div class="flex flex-justify-between">
          <el-form-item prop="modelFile" label="选择模型文件">
            <el-button type="primary" :disabled="loading" @click="handleOpenUploadFileDialog(1)">选择文件</el-button>
            <el-button type="primary" :disabled="loading" @click="handleOpenUploadFileDialog(5)">批量选择</el-button>
            <span class="ml2 font-size-2.8 c-#999999">注：只有当输入模型格式一致、输出模型格式一致时才能批量操作</span>
          </el-form-item>
          <el-form-item prop="setConversionParameters" label="设置转换参数">
            <el-button type="primary" :disabled="loading" @click="handleParameterSettingDialog">参数设置</el-button>
          </el-form-item>
        </div>
        <el-table :data="tableFileDatas">
          <el-table-column prop="sourceFileName" label="源文件名称"> </el-table-column>
          <el-table-column prop="fileSize" label="文件大小"> </el-table-column>
          <el-table-column prop="inputModel" label="输入模型"> </el-table-column>
          <el-table-column prop="outputModel" label="输出模型"> </el-table-column>
          <el-table-column prop="createTime" label="创建时间"> </el-table-column>
          <el-table-column prop="status" label="转换状态">
            <template #default="scope">
              {{ convertStatus[scope.row.status] }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button type="text" :disabled="loading" @click="handleDelete(scope.row, scope.$index)">删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="text-center">
        <el-button size="large" type="primary" :disabled="loading" @click="handleOpenProgressDialog">开始转换</el-button>
        <!-- <el-button size="small" type="primary" :disabled="loading" plain @click="handleOpenOperationLogDialog">查看运行日志</el-button> -->
      </div>
    </el-form>
    <div v-if="progressVisible" class="block-progress">
      <el-progress type="circle" :percentage="progress" />
    </div>
    <upload-file-dialog ref="uploadFileDialogRef" :accept="accept" :limit="limit" @on-sure="handleUploadSure" @on-sure2="handleUploadSure2" />
    <parameter-setting-dialog ref="parameterSettingDialogRef" />
    <operation-log-dialog ref="operationLogDialogRef" />
    <!-- <progress-dialog ref="progressDialogRef" /> -->
  </div>
</template>

<script setup name="CadConversion" lang="ts">
import type { UploadProps, FormRules } from 'element-plus';
import { caeOutputConversionForm } from '@/api/caxDataConversionMajorComponent/formatConversionManagement/caeOutputConversion/type';
import { optionType, inputModelType, outputModelType } from '@/api/caxDataConversionMajorComponent/type';
import { parseTime } from '@/utils/ruoyi';
import UploadFileDialog from './uploadFileDialog.vue';
import ParameterSettingDialog from './parameterSettingDialog.vue';
import OperationLogDialog from './operationLogDialog.vue';
import ProgressDialog from './progressDialog.vue';
import { caxConvertInfo, caxConvertInfo2 } from '@/api/caxDataConversionMajorComponent/formatConversionManagement/index';
const { proxy } = getCurrentInstance();
const disabled = ref(true);
const loading = ref(false);
const progressVisible = ref(false);
const progress = ref(10);
const caeInputModelTypes = ref<Array<inputModelType>>([
  {
    inputModel: 'bdf',
    outputModel: ['inp', 'cdb', 'vtk', 'gmesh'],
    accept: '.bdf'
  },
  {
    inputModel: 'inp',
    outputModel: ['bdf', 'cdb', 'vtk', 'gmesh'],
    accept: '.inp'
  },
  {
    inputModel: 'cdb',
    outputModel: ['bdf', 'inp', 'vtk', 'gmesh'],
    accept: '.cdb'
  }
]);
const caeOutputModelTypes = ref<Array<outputModelType>>([
  {
    disabled: true,
    label: 'bdf'
  },
  {
    disabled: true,
    label: 'inp'
  },
  {
    disabled: true,
    label: 'cdb'
  },
  {
    disabled: true,
    label: 'vtk'
  },
  {
    disabled: true,
    label: 'gmesh'
  }
]);
const caeConversionFormData = reactive<caeOutputConversionForm>({
  caeInputModelType: '',
  caeOutputModelType: '',
  modelFile: null,
  setConversionParameters: {}
});
const convertStatus = ['转换中', '转换成功', '转换失败', '待转换'];
const accept = ref('');
const limit = ref(1);
const rules = reactive<FormRules<caeOutputConversionForm>>({
  caeInputModelType: [{ required: true, message: '请选择输入模型格式', trigger: 'change' }],
  caeOutputModelType: [{ required: true, message: '请选择输出模型格式', trigger: 'change' }],
  modelFile: [{ required: true, message: '请选择文件', trigger: 'change' }],
  setConversionParameters: [{ required: true, message: '请选择设置转换参数', trigger: 'change' }]
});
const tableFileDatas = ref([]);
const files = ref([]);
const uploadFileDialogRef = ref<ElDialogInstance>();
const parameterSettingDialogRef = ref<ElDialogInstance>();
const operationLogDialogRef = ref<ElDialogInstance>();
const progressDialogRef = ref<ElDialogInstance>();
const handleOpenUploadFileDialog = async (num) => {
  if (!caeConversionFormData.caeInputModelType) {
    await proxy?.$modal.msgWarning('请选择输入模型模式！');
    return false;
  }
  if (!caeConversionFormData.caeOutputModelType) {
    await proxy?.$modal.msgWarning('请选择输出模型模式！');
    return false;
  }
  limit.value = num;
  uploadFileDialogRef.value.openDialog();
};
const handleParameterSettingDialog = () => {
  parameterSettingDialogRef.value.openDialog();
};
const handleOpenOperationLogDialog = () => {
  operationLogDialogRef.value.openDialog();
};
const handleOpenProgressDialog = async () => {
  if (!tableFileDatas.value.length) {
    await proxy?.$modal.msgWarning('请选择上传文件！');
  }
  loading.value = true;
  tableFileDatas.value.forEach(async (element, index) => {
    const formData = new FormData();
    formData.append('convertType', 'CAE_INPUT');
    formData.append('inputType', caeConversionFormData.caeInputModelType);
    formData.append('outputType', caeConversionFormData.caeOutputModelType);
    if (element.file) {
      formData.append('file', element.file);
      element.status = 0;
      caxConvertInfo(formData)
        .then((res) => {
          if (res.code === 200) {
            element.status = 1;
            proxy?.$modal.msgSuccess(element.sourceFileName + '转换完成！');
          } else {
            element.status = 2;
            proxy?.$modal.msgError(element.sourceFileName + '转换失败！');
          }
        })
        .catch(() => {
          element.status = 2;
        });
    }
    if (element.fileId) {
      formData.append('sourceFileId', element.fileId);
      element.status = 0;
      caxConvertInfo2(formData)
        .then((res) => {
          if (res.code === 200) {
            element.status = 1;
            proxy?.$modal.msgSuccess(element.sourceFileName + '转换完成！');
          } else {
            element.status = 2;
            proxy?.$modal.msgError(element.sourceFileName + '转换失败！');
          }
        })
        .catch(() => {
          element.status = 2;
        });
    }
  });
  tableFileDatas.value = [];
  loading.value = false;
};
const handleRadioChange = () => {
  const obj = caeInputModelTypes.value.find((item) => item.inputModel === caeConversionFormData.caeInputModelType);
  if (obj) {
    accept.value = obj.accept;
    const arr = obj.outputModel;
    caeOutputModelTypes.value.forEach((element) => {
      if (arr.includes(element.label)) {
        element.disabled = false;
      } else {
        element.disabled = true;
      }
    });
    caeConversionFormData.caeOutputModelType = '';
  }
};
const getSizeStr = (size) => {
  if (size < 1024) {
    return size + 'B';
  } else if (size > 1023 && size < 1024 * 1024) {
    return Number(size / 1024).toFixed(2) + 'kB';
  } else {
    return Number(size / 1024 / 1024).toFixed(2) + 'MB';
  }
};
const handleUploadSure = (datas) => {
  if (tableFileDatas.value.length < 5) {
    const arr = datas.map((item) => {
      return {
        sourceFileName: item.name,
        fileSize: getSizeStr(item.size),
        inputModel: caeConversionFormData.caeInputModelType,
        outputModel: caeConversionFormData.caeOutputModelType,
        createTime: parseTime(new Date()),
        status: 3,
        file: item.raw
      };
    });
    let len = arr.length;
    if (5 - tableFileDatas.value.length < arr.length) {
      len = 5 - tableFileDatas.value.length;
      proxy?.$modal.msgWarning(`支持添加5个文件,已有${tableFileDatas.value.length}个文件，仅支持添加${5 - tableFileDatas.value.length}个文件`);
    }
    for (let i = 0; i < len; i++) {
      tableFileDatas.value.push(arr[i]);
    }
  } else {
    proxy?.$modal.msgWarning(`仅支持添加5个文件`);
  }
};
const handleUploadSure2 = (datas) => {
  if (tableFileDatas.value.length < 5) {
    const arr = datas.map((item) => {
      return {
        sourceFileName: item.name,
        fileSize: getSizeStr(item.size),
        inputModel: caeConversionFormData.caeInputModelType,
        outputModel: caeConversionFormData.caeOutputModelType,
        createTime: parseTime(new Date()),
        status: 3,
        fileId: item.id
      };
    });
    let len = arr.length;
    if (5 - tableFileDatas.value.length < arr.length) {
      len = 5 - tableFileDatas.value.length;
      proxy?.$modal.msgWarning(`支持添加5个文件,已有${tableFileDatas.value.length}个文件，仅支持添加${5 - tableFileDatas.value.length}个文件`);
    }
    for (let i = 0; i < len; i++) {
      tableFileDatas.value.push(arr[i]);
    }
  } else {
    proxy?.$modal.msgWarning(`仅支持添加5个文件`);
  }
};
const handleDelete = async (row, index) => {
  if (!row.status) {
    await proxy?.$modal.msgWarning('数据转换中，不允许删除！');
    return false;
  }
  await proxy?.$modal.confirm('是否确认删除该数据');
  tableFileDatas.value.splice(index, 1);
};
</script>
<style lang="scss" scoped>
.block-progress {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}
</style>
